import {ChangeDetectorRef, Component, ViewChild} from '@angular/core';
import {Content, IonicPage, NavController, NavParams, Select, ToastController} from 'ionic-angular';
import {InfiniteScrollModel} from "../../../model/common/infinite-scroll.model";
import {CallNumber} from "@ionic-native/call-number";
import {CallNumberService} from "../../../services/native/call-number/call-number.service";
import {ClientFilterComponent} from "../../../components/pages/client/client-filter/client-filter.component";
import {LoadingService} from "../../../services/common/loading.service";
import {MessageBushService} from "../../../services/common/message-bush.service";
import {ClientNoteEditProvider} from "../../../providers/client/client-note/client-note-edit/client-note-edit.provider";
import {TabsPage} from "../../tabs/tabs";
import {SideMenuService} from "../../../services/common/side-menu.service";
import {ClientFilterWayModel} from "../../../model/pages/client/client-list/client.model";
import {ClientIndividualProvider} from "../../../providers/client/client-individual/client-individual.provider";
import {AdpActionSheetController} from "../../../components/common/adp-action-sheet/adp-action-sheet-controller";
import $ from 'jquery';

@IonicPage()
@Component({
    selector: 'page-client-single',
    templateUrl: 'client-single.html',
    providers: [
        CallNumber,
        ClientIndividualProvider,
        ClientNoteEditProvider,
        TabsPage,
        SideMenuService,
        CallNumberService
    ]
})
export class ClientSinglePage extends InfiniteScrollModel {

    infiniteScroll = null;
    searchKeyword: string;
    isLoaded: boolean = false;
    @ViewChild(Content) content: Content;
    clientsData = [];
    dataTotal: string;

    get clientItemHeight(): string {
        const windowW = window['innerWidth'];
        return (windowW * 38.34 / 100) + 'px';
    }

    get headerHeight(): string {
        return 10 + 'px'
    }

    currentMobileList;
    currentMobile;
    currentClient;
    isScrolling = false;
    isViewDidLoad = false;
    isArriveBottom = false;
    @ViewChild('clientFilterTool') clientFilterTool: ClientFilterComponent;
    clientSortPage = ClientFilterWayModel.ClientIndividualListPage;
    $ionList;
    dataItemSearchWrapper = {
        isSearchWrapper:true
    };
    //正在刷新
    refreshing:boolean = false;

    constructor(public individualProvider: ClientIndividualProvider,
                private callNumber: CallNumber,
                public navCtrl: NavController,
                public navParams: NavParams,
                private clientNoteEditProvider: ClientNoteEditProvider,
                public toastCtrl: ToastController,
                private sideMenuService: SideMenuService,
                public changeRef: ChangeDetectorRef,
                public tabsPage: TabsPage,
                private callNumberService: CallNumberService,
                public adpActionSheetController:AdpActionSheetController,
                public loadService: LoadingService) {
        super();
    }

    ionViewDidLoad() {
        this.isViewDidLoad = true;
        this.loadingClientListData();
    }

    ionViewDidEnter() {
        const flag = MessageBushService.getMessage(MessageBushService.keys.clientIndividualClientUpdated);
        if (flag == '1' && !this.isViewDidLoad) {
            this.getFirstPageData(0);
        }
        this.isViewDidLoad = false;
        this.$ionList = $('.client-single');
    }


    openRoot = (name, index) => this.openTab(name, index);

    openMenu(myEvent) {
        this.sideMenuService.openSideMenu(myEvent)
    }

    openTab(name, index) {
        this.navCtrl.popToRoot();
        this.tabsPage.openPage({name: name, index: index});
    }

    scrolling() {
        const dimensions = this.content.getContentDimensions();
        if((!this.clientsData || this.clientsData.length < 2) && this.isLoaded){
            return;
        }
        const temp1 = dimensions.scrollHeight - dimensions.scrollTop - dimensions.contentHeight < 100;
        if (temp1 !== this.isArriveBottom && this.$ionList.height() > dimensions.contentHeight) {
            this.isArriveBottom = temp1;
            this.changeRef.detectChanges();
        }

    }

    scrollStart(e) {
        this.isScrolling = true;
    }

    scrollEnd(e) {
        this.isScrolling = false;
    }

    filterConditionsShow = true;

    contentTouchEnd() {
        setTimeout(() => {
            if(!this.refreshing) {
                this.filterConditionsShow = true;
            }
        }, 500);
    }

    /**
     * 获取首页数据
     * @returns {Promise<void>}
     */
    getFirstPageData(notloading = 0, callback = null) {
        this.isLoaded = false;
        this.isArriveBottom = false;
        const personTotal = this.navParams.get('personalInsurance');
        this.pageParams.pageNum = 1;
        this.pageParams.pageSize = personTotal || 20;
        return this.individualProvider.getIndividualPageList(notloading, this.pageParams).subscribe(res => {
                this.pageInfo = res;
                this.isLoaded = true;
                this.dataTotal = `(${this.pageInfo.total})`;
                if (this.pageInfo.list && this.pageInfo.list.length) {
                    this.clientsData = this.pageInfo.list;
                    //过滤为空的电话号码
                    this.clientsData = this.individualProvider.checkMobileNull(this.clientsData);
                } else {
                    this.clientsData = [];
                }
                if(this.clientsData.indexOf(this.dataItemSearchWrapper)==-1){
                    this.clientsData.unshift(this.dataItemSearchWrapper);
                }
                if (callback) {
                    callback();
                }
            },
            error => {
                if(this.clientsData.indexOf(this.dataItemSearchWrapper)==-1){
                    this.clientsData.unshift(this.dataItemSearchWrapper);
                }
                if (callback) {
                    callback();
                }
            });
    }


    /**
     *  toast 提示信息
     * @param {string} message 提示内容
     * @param {string} position 显示位置
     */
    toast(message: string, position: string) {
        this.toastCtrl.create({
            message: message,
            position: 'middle',
            duration: 1200
        }).present();
    }

    goUp() {
        if (this.isScrolling) {
            setTimeout(() => {
                this.goUp();
            }, 300);
            return;
        }
        this.content.scrollToTop();
    }

    /**
     * 后退
     */
    backHandle() {
        this.navCtrl.pop();
    }

    // 到客户详情
    goToDetail(clientNum) {
        this.navCtrl.push('HolderClientDetailPage', {
            clientNum: clientNum
        })
    }


    //调用原生打电话
    nativeCallPhone(mobilePhone?: string) {
        if (mobilePhone) {
            this.currentMobile = mobilePhone;
        }
        this.callNumberService.makeCall(this.currentMobile,
            this.callNumberService.initClientNoteLog(this.currentClient.clientId),
            true,
            this.callNumberService.initFollowStateLog(this.currentClient.clientId));
    }

    /**
     * 打电话
     */
    callClickHandle(item) {
        this.currentClient = item;
        this.currentMobileList = item.mobilePhone;
        if (!this.currentMobileList || this.currentMobileList.length < 1) return;
        if (this.currentMobileList.length === 1 && this.currentMobileList[0].mobile) {
            this.currentMobile = this.currentMobileList[0].mobile;
            this.nativeCallPhone();
            return;
        }else{
            const phoneArray = [];
            this.currentMobileList.forEach(phoneNumItem => {
                phoneArray.push({
                    text:phoneNumItem.mobile,
                    handler:() => {
                        this.currentMobile = phoneNumItem.mobile;
                        this.nativeCallPhone();
                    }
                });
            });
            this.adpActionSheetController.create({
                title:"选择电话",
                buttons:phoneArray
            }).present();
        }

    }

    /**
     * 下拉刷新
     * @param refresher
     */
    doRefresh(refresher) {
        this.refreshing = true;
        this.pageParams.pageNum = 1;
        if (this.infiniteScroll) this.infiniteScroll.enable(true);
        this.getFirstPageData(1, () => {
            this.refreshing = false;
            this.filterConditionsShow = true;
            refresher.complete();
        });
    }

    searchedHandle(searchKeyword){
        this.searchKeyword = searchKeyword;
        this.pageParams.pageNum = 1;
        if (this.infiniteScroll) this.infiniteScroll.enable(true);
        if (this.searchKeyword) {
            this.pageParams.condition.keyword = this.searchKeyword.trim();
        } else {
            this.pageParams.condition.keyword = '';
        }
        this.loadingClientListData();
    }

    selectChangeHandle(e) {
        this.pageParams.orderType = e.value;
        this.loadingClientListData();
    }

    loadingClientListData() {
        this.loadService.showLoading();
        this.getFirstPageData(0, () => {
            this.loadService.dismissLoading();
        });
    }

    ionViewWillLeave() {
        this.clientFilterTool.destroy();
    }

    /**
     * 输入框键盘事件
     * @param e
     */
    inputKeyUp(e) {
        if ('Enter' === e.key || 13 === e.keyCode) {
          //  this.searched.emit(this.searchKeyword);
            this.pageParams.pageNum = 1;
            if (this.infiniteScroll) this.infiniteScroll.enable(true);
            if (this.searchKeyword) {
                this.pageParams.condition.keyword = this.searchKeyword.trim();
            } else {
                this.pageParams.condition.keyword = '';
            }
        }
    }


    searchHandle(ev) {
        ev.preventDefault();
        ev.stopPropagation();
        this.inputKeyUp({key: 'Enter'});
    }


}
